/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.infor.entity.BudgetExpen;
import com.jeeplus.modules.infor.entity.RentDetil;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.Planning;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.StoreBudget;
import com.jeeplus.modules.infor.service.StoreBudgetService;

/**
 * 仓租收支明细Controller
 * @author 李超辉
 * @version 2019-02-13
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/storeBudget")
public class StoreBudgetController extends BaseController {

	@Autowired
	private StoreBudgetService storeBudgetService;
	@Autowired
	private SlService slService;
	
	@ModelAttribute
	public StoreBudget get(@RequestParam(required=false) String id) {
		StoreBudget entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = storeBudgetService.get(id);
		}
		if (entity == null){
			entity = new StoreBudget();
		}
		return entity;
	}
	
	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/infor/5/storeBudgetList";
	}
	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/infor/3/storeBudgetList";
	}


	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/infor/2/storeBudgetList";
	}
	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value = {"list5"})
	public String list5() {
		return "modules/infor/1/storeBudgetList";
	}

	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value = {"list6"})
	public String list6() {
		return "modules/infor/6/storeBudgetList";
	}
	/**
	 * 仓租收支明细列表页面
	 */
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/infor/4/storeBudgetList";
	}
	/**
	 *
	 * 仓租收支明细列表页面
	 */
	@RequiresPermissions("infor:storeBudget:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/storeBudgetList";
	}
		/**
	 * 仓租收支明细列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:storeBudget:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(StoreBudget storeBudget, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			storeBudget.setPro(pro);
		}
		Page<StoreBudget> page = storeBudgetService.findPage(new Page<StoreBudget>(request, response), storeBudget);
		return getBootstrapData(page);
	}

	/**
	 * 仓租收支明细列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(StoreBudget storeBudget, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			storeBudget.setPro(pro);
		}
		storeBudget.setDjzt("已确认");
		Page<StoreBudget> page = storeBudgetService.findPage(new Page<StoreBudget>(request, response), storeBudget);
		return getBootstrapData(page);
	}
	/**
	 * 办事处
	 */
	@ResponseBody
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(StoreBudget storeBudget, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			storeBudget.setPro(pro);
		}
		storeBudget.setDjzt("已确认");
		Page<StoreBudget> page = storeBudgetService.findPage2(new Page<StoreBudget>(request, response), storeBudget);
		return getBootstrapData(page);
	}

	/**
	 * 年报表
	 */
	@ResponseBody
	@RequestMapping(value = "data4")
	public Map<String, Object> data4(StoreBudget storeBudget, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			storeBudget.setPro(pro);
		}
		storeBudget.setDjzt("已确认");
		Page<StoreBudget> page = storeBudgetService.findPage3(new Page<StoreBudget>(request, response), storeBudget);
		return getBootstrapData(page);
	}

	/**
	 * 按月汇总
	 */
	@ResponseBody
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(StoreBudget storeBudget, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			storeBudget.setPro(pro);
		}
		storeBudget.setDjzt("已确认");
		Page<StoreBudget> page = storeBudgetService.findPage1(new Page<StoreBudget>(request, response), storeBudget);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑仓租收支明细表单页面
	 */
	@RequiresPermissions(value={"infor:storeBudget:view","infor:storeBudget:add","infor:storeBudget:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(StoreBudget storeBudget, Model model) {
		if(storeBudget.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				storeBudget.setPro(pro);
			}
			storeBudget.setBsc(UserUtils.getbsc());
			storeBudget.setDjzt("已创建");
			storeBudget.setKpzt("未开票");
			storeBudget.setJszt("未结算");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			StoreBudget p=new StoreBudget();
			p.setDjh(code);
			List<StoreBudget> l=storeBudgetService.findList(p);
			if(l==null||l.size()<1){
				storeBudget.setDjh(code+"001"+"CZSZ");
			}else{
				if(l.size()/10==0){
					storeBudget.setDjh(code+"00"+(l.size()+1)+"CZSZ");
				}else
				if(l.size()/100==0){
					storeBudget.setDjh(code+"0"+(l.size()+1)+"CZSZ");
				}else{storeBudget.setDjh(code+(l.size()+1)+"CZSZ");}

			}
		}

		model.addAttribute("storeBudget", storeBudget);
		return "modules/infor/storeBudgetForm";
	}

	/**
	 * 保存仓租收支明细
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:storeBudget:add","infor:storeBudget:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(StoreBudget storeBudget, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, storeBudget)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		List<BudgetExpen>  l=storeBudget.getBudgetExpenList();
		double e=0.0;
		for(BudgetExpen b:l){
			if(b.getType().equals("罚款")){
				e+=Double.parseDouble(b.getJe());
			}
		}
		storeBudget.setFk(e+"");
		//新增或编辑表单保存
		storeBudget.setYf("0");
		storeBudget.setWf(storeBudget.getZzc());
		storeBudgetService.save(storeBudget);//保存
		j.setSuccess(true);
		j.setMsg("保存仓租收支明细成功");
		return j;
	}
	
	/**
	 * 删除仓租收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:storeBudget:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(StoreBudget storeBudget, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		storeBudgetService.delete(storeBudget);
		j.setMsg("删除仓租收支明细成功");
		return j;
	}
	/**
	 * 确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(StoreBudget storeBudget, RedirectAttributes redirectAttributes) {
		DecimalFormat df = new DecimalFormat("0.00%");
		AjaxJson j = new AjaxJson();
		storeBudget.setDjzt("已确认");
		Sl sl=slService.findUniqueByProperty("pro",storeBudget.getPro());
		sl=slService.get(sl.getId());
		double sj=Double.parseDouble(storeBudget.getZsr())*Double.parseDouble(sl.getSl());
		double mlr=Double.parseDouble(storeBudget.getZsr())-Double.parseDouble(storeBudget.getZzc())-sj;
		double lrl=mlr/Double.parseDouble(storeBudget.getZsr());
		storeBudget.setSj(sj+"");
		storeBudget.setMlr(mlr+"");
		storeBudget.setLrl(df.format(lrl));
		storeBudget.setZzsl(sl.getSl());
		storeBudgetService.save(storeBudget);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 付款
	 */
	@ResponseBody
	@RequestMapping(value = "fk")
	public String fk(StoreBudget storeBudget, String fkrq,String fph, RedirectAttributes redirectAttributes) throws ParseException {
		NumberFormat nf = NumberFormat.getInstance();
		storeBudget.setJszt("已结算");
		storeBudget.setZckpje(storeBudget.getZzc());
		storeBudget.setZcfph(fph);
		storeBudget.setYf(storeBudget.getZzc());
		SimpleDateFormat bf = new SimpleDateFormat("yyyy-MM-dd");
		storeBudget.setFkrq(bf.parse(fkrq));
		storeBudgetService.save(storeBudget);

		return "";
	}
	/**
	 * 确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qxqr")
	public AjaxJson qxqr(StoreBudget storeBudget, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		storeBudget.setDjzt("已创建");
		storeBudgetService.save(storeBudget);
		j.setMsg("取消确认成功");
		return j;
	}
	/**
	 * 批量删除仓租收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:storeBudget:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			storeBudgetService.delete(storeBudgetService.get(id));
		}
		j.setMsg("删除仓租收支明细成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:storeBudget:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(StoreBudget storeBudget, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "仓租收支明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<StoreBudget> page = storeBudgetService.findPage(new Page<StoreBudget>(request, response, -1), storeBudget);
    		new ExportExcel("仓租收支明细", StoreBudget.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出仓租收支明细记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public StoreBudget detail(String id) {
		return storeBudgetService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:storeBudget:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<StoreBudget> list = ei.getDataList(StoreBudget.class);
			for (StoreBudget storeBudget : list){
				try{
					storeBudgetService.save(storeBudget);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条仓租收支明细记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条仓租收支明细记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入仓租收支明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/storeBudget/?repage";
    }
	
	/**
	 * 下载导入仓租收支明细数据模板
	 */
	@RequiresPermissions("infor:storeBudget:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "仓租收支明细数据导入模板.xlsx";
    		List<StoreBudget> list = Lists.newArrayList(); 
    		new ExportExcel("仓租收支明细数据", StoreBudget.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/storeBudget/?repage";
    }
	

}